import api from '@/utils/request'
import axios from 'axios'

// 文献相关接口类型定义
export interface Literature {
  id: number
  title: string
  authors: string
  abstractText: string
  keywords: string
  journal: string
  publicationDate: string
  doi: string
  fileName: string
  fileSize: number
  fileType: string
  status: number
  recognitionStatus: number
  uploadUserId: number
  uploadUserName: string
  createTime: string
  updateTime: string
  isFavorite: boolean
}

export interface LiteratureQuery {
  title?: string
  authors?: string
  keywords?: string
  journal?: string
  status?: number
  recognitionStatus?: number
  uploadUserId?: number
  current?: number
  size?: number
  sortField?: string
  sortOrder?: string
}

export interface PageResult<T> {
  records: T[]
  total: number
  size: number
  current: number
  pages: number
}

// 文献API
export const literatureApi = {
  // 上传文献
  upload(formData: FormData): Promise<number> {
    // 创建一个新的axios实例，专门用于文件上传
    const uploadApi = axios.create({
      baseURL: 'http://localhost:10003', // API网关地址，修复：使用API网关而不是直接连接服务
      timeout: 10000,
      // 不设置Content-Type，让浏览器自动设置
      headers: {}
    });
    
    // 添加认证token
    const token = localStorage.getItem('token');
    if (token) {
      uploadApi.defaults.headers.common['Authorization'] = `Bearer ${token}`;
    }
    
    return uploadApi.post('/document-service/literature/upload', formData);
  },

  // 获取文献列表
  getList(query: LiteratureQuery): Promise<PageResult<Literature>> {
    return api.post('/document-service/literature/list', query)
  },

  // 获取文献详情
  getById(id: number): Promise<Literature> {
    return api.get(`/document-service/literature/${id}`)
  },

  // 更新文献信息
  update(id: number, data: Partial<Literature>): Promise<void> {
    return api.put(`/document-service/literature/${id}`, data)
  },

  // 删除文献
  delete(id: number): Promise<void> {
    return api.delete(`/document-service/literature/${id}`)
  },

  // 下载文献
  download(id: number): Promise<void> {
    return api.get(`/document-service/literature/${id}/download`, {
      responseType: 'blob'
    }).then((response: any) => {
      const blob = new Blob([response.data])
      const url = window.URL.createObjectURL(blob)
      const link = document.createElement('a')
      link.href = url
      
      // 从响应头获取文件名
      const contentDisposition = response.headers['content-disposition']
      let fileName = `literature_${id}.pdf`
      if (contentDisposition) {
        const matches = contentDisposition.match(/filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/)
        if (matches && matches[1]) {
          fileName = decodeURIComponent(matches[1].replace(/['"]/g, ''))
        }
      }
      
      link.download = fileName
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      window.URL.revokeObjectURL(url)
    })
  },

  // 收藏/取消收藏
  toggleFavorite(id: number): Promise<void> {
    return api.post(`/document-service/literature/${id}/favorite`)
  },

  // 获取收藏列表
  getFavorites(query: LiteratureQuery): Promise<PageResult<Literature>> {
    return api.post('/document-service/literature/favorites', query)
  },
  
  // 手动触发文献识别（管理员功能）
  triggerRecognition(id: number): Promise<void> {
    return api.post(`/document-service/literature/${id}/recognize`)
  }
}